import { CookieManager, CookieData } from './CookieManager';

export interface TabSession {
  tabId: string;
  accountId?: string;
  cookies: CookieManager;
  localStorage: Map<string, any>;
  sessionStorage: Map<string, any>;
  userAgent?: string;
  createdAt: Date;
  lastActive: Date;
}

export interface TabConfig {
  accountId?: string;
  platform?: string;
  userAgent?: string;
  initialUrl?: string;
  isolationLevel?: 'full' | 'cookie-only' | 'none';
}

export class TabManager {
  private sessions: Map<string, TabSession> = new Map();
  private defaultUserAgents: Record<string, string> = {
    '抖音': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
    '快手': 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36',
    '小红书': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15',
    '微博': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'B站': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
  };

  // 创建新标签页会话
  createSession(tabId: string, config: TabConfig = {}): TabSession {
    const userAgent = config.userAgent || this.getDefaultUserAgent(config.platform);
    
    const session: TabSession = {
      tabId,
      accountId: config.accountId,
      cookies: new CookieManager(tabId),
      localStorage: new Map(),
      sessionStorage: new Map(),
      userAgent,
      createdAt: new Date(),
      lastActive: new Date()
    };

    this.sessions.set(tabId, session);
    this.saveSessionToStorage(session);
    
    return session;
  }

  // 获取标签页会话
  getSession(tabId: string): TabSession | undefined {
    const session = this.sessions.get(tabId);
    if (!session) {
      return this.loadSessionFromStorage(tabId);
    }
    return session;
  }

  // 销毁标签页会话
  destroySession(tabId: string): void {
    const session = this.sessions.get(tabId);
    if (session) {
      // 清理存储
      localStorage.removeItem(`tab_session_${tabId}`);
      localStorage.removeItem(`tab_cookies_${tabId}`);
      localStorage.removeItem(`tab_localStorage_${tabId}`);
      
      this.sessions.delete(tabId);
    }
  }

  // 更新会话活跃时间
  updateSessionActivity(tabId: string): void {
    const session = this.getSession(tabId);
    if (session) {
      session.lastActive = new Date();
      this.saveSessionToStorage(session);
    }
  }

  // 设置Cookie
  setCookie(tabId: string, cookie: CookieData): void {
    const session = this.getSession(tabId);
    if (session) {
      session.cookies.setCookie(cookie);
      this.updateSessionActivity(tabId);
    }
  }

  // 获取Cookie
  getCookie(tabId: string, name: string): CookieData | undefined {
    const session = this.getSession(tabId);
    return session?.cookies.getCookie(name);
  }

  // 导出标签页所有Cookie
  exportCookies(tabId: string): string {
    const session = this.getSession(tabId);
    return session?.cookies.exportCookies() || '[]';
  }

  // 导入Cookie到标签页
  importCookies(tabId: string, cookieJson: string): void {
    const session = this.getSession(tabId);
    if (session) {
      session.cookies.importCookies(cookieJson);
      this.updateSessionActivity(tabId);
    }
  }

  // 清除标签页所有Cookie
  clearCookies(tabId: string): void {
    const session = this.getSession(tabId);
    if (session) {
      session.cookies.clearAll();
      this.updateSessionActivity(tabId);
    }
  }

  // 生成特定标签页的Cookie请求头
  generateCookieHeader(tabId: string, url: string): string {
    const session = this.getSession(tabId);
    return session?.cookies.generateCookieHeader(url) || '';
  }

  // 解析Set-Cookie响应头并存储
  parseSetCookieHeader(tabId: string, setCookieHeader: string, url: string): CookieData[] {
    const session = this.getSession(tabId);
    if (session) {
      const cookies = session.cookies.parseSetCookieHeader(setCookieHeader, url);
      this.updateSessionActivity(tabId);
      return cookies;
    }
    return [];
  }

  // 设置localStorage项
  setLocalStorage(tabId: string, key: string, value: any): void {
    const session = this.getSession(tabId);
    if (session) {
      session.localStorage.set(key, value);
      this.saveLocalStorageToStorage(session);
      this.updateSessionActivity(tabId);
    }
  }

  // 获取localStorage项
  getLocalStorage(tabId: string, key: string): any {
    const session = this.getSession(tabId);
    return session?.localStorage.get(key);
  }

  // 获取所有活跃会话
  getAllSessions(): TabSession[] {
    return Array.from(this.sessions.values());
  }

  // 根据账号ID查找会话
  findSessionsByAccount(accountId: string): TabSession[] {
    return this.getAllSessions().filter(session => session.accountId === accountId);
  }

  // 获取平台特定的User-Agent
  private getDefaultUserAgent(platform?: string): string {
    if (platform && this.defaultUserAgents[platform]) {
      return this.defaultUserAgents[platform];
    }
    return 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
  }

  // 保存会话到本地存储
  private saveSessionToStorage(session: TabSession): void {
    const sessionData = {
      tabId: session.tabId,
      accountId: session.accountId,
      userAgent: session.userAgent,
      createdAt: session.createdAt.toISOString(),
      lastActive: session.lastActive.toISOString()
    };
    
    localStorage.setItem(`tab_session_${session.tabId}`, JSON.stringify(sessionData));
  }

  // 从本地存储加载会话
  private loadSessionFromStorage(tabId: string): TabSession | undefined {
    try {
      const sessionData = localStorage.getItem(`tab_session_${tabId}`);
      if (!sessionData) return undefined;

      const parsed = JSON.parse(sessionData);
      const session: TabSession = {
        tabId: parsed.tabId,
        accountId: parsed.accountId,
        cookies: new CookieManager(tabId),
        localStorage: this.loadLocalStorageFromStorage(tabId),
        sessionStorage: new Map(),
        userAgent: parsed.userAgent,
        createdAt: new Date(parsed.createdAt),
        lastActive: new Date(parsed.lastActive)
      };

      this.sessions.set(tabId, session);
      return session;
    } catch (error) {
      console.error('加载会话失败:', error);
      return undefined;
    }
  }

  // 保存localStorage到本地存储
  private saveLocalStorageToStorage(session: TabSession): void {
    const localStorageArray = Array.from(session.localStorage.entries());
    localStorage.setItem(`tab_localStorage_${session.tabId}`, JSON.stringify(localStorageArray));
  }

  // 从本地存储加载localStorage
  private loadLocalStorageFromStorage(tabId: string): Map<string, any> {
    try {
      const stored = localStorage.getItem(`tab_localStorage_${tabId}`);
      if (stored) {
        const array = JSON.parse(stored) as [string, any][];
        return new Map(array);
      }
    } catch (error) {
      console.error('加载localStorage失败:', error);
    }
    return new Map();
  }
}